#!/bin/sh

cat > /tmp/indenter.el <<EOF
(defun batch-c-indent ()
  "Run batch-c-indent: xemacs -batch -i indenter.el -f batch-c-indent *.c"
  (if (not noninteractive)
      (error "batch-c-indent' for xemacs -batch only."))
  
  
  (add-hook 'c-mode-hook
	    (function (lambda ()
                        (c-set-offset 'inclass' ++)
                        (c-set-offset 'defun-block-intro' ++)
                        (c-set-offset 'statement-block-intro' ++)
                        (c-set-offset 'substatement' ++)
                        (c-set-offset 'brace-list-intro' ++)
                        (c-set-offset 'statement-case-intro' ++)
                        (c-set-offset 'inextern-lang' 0)
                        )))
  (setq c++-mode-hook c-mode-hook)
  (while command-line-args-left
    (let ((source (car command-line-args-left)))
      (find-file source)
      (indent-region (point-min) (point-max) (c-mode))
      (write-file source))
    (setq command-line-args-left (cdr command-line-args-left)))
  (message "done.")
  (kill-emacs 0))

(defun batch-java-indent ()
  "Run batch-java-indent: xemacs -batch -i indenter.el -f batch-java-indent *.java"
  (if (not noninteractive)
      (error "batch-c-indent' for xemacs -batch only."))
  (setq-default indent-tabs-mode nil)
  (c-add-style
   "eease" '("java" (c-basic-offset . 2)
	     (c-offsets-alist . ((substatement-open . 0)))))
  (setq java-mode-hook (lambda () (c-set-style "eease")))
  (while command-line-args-left
    (let ((source (car command-line-args-left)))
      (find-file source)
      (indent-region (point-min) (point-max) (java-mode))
      (write-file source))
    (setq command-line-args-left (cdr command-line-args-left)))
  (message "done.")
  (kill-emacs 0))
EOF

echo "looking for xemacs"
EMACS=`which xemacs`
if [ "x$EMACS" = "x" ]
then
	echo "looking for emacs"
	EMACS=`which emacs`
	if [ "x$EMACS" = "x" ]
	then
		echo "no emacs found."
	else
		echo "found: $EMACS"
	fi
else
	echo "found: $EMACS"
fi

MODE="none"
if [ "x$1" != "x" ]
then
	MODE="$1"
	shift 1
fi

if [ "$MODE" = "-c" ]
then
	$EMACS -batch -l /tmp/indenter.el -f batch-c-indent $@
elif  [ "$MODE" = "-java" -o "$MODE" = "-j" ]
then
	$EMACS -batch -l /tmp/indenter.el -f batch-java-indent $@
else
	echo "usage: indenter.sh {-c|-j|-java} [files] where -option is mode"
fi
